from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from contextlib import asynccontextmanager
from app.config import mount_settings_to_app, STATIC_IMG_FOLDER, get_settings
from app.database import postgre, redis
from app.routers import backend as backend_router, develop as develop_router, faker as faker_router
from app.middlewares import backend as backend_middlewares, develop as develop_middlewares
from app.utils import FM

# 生命周期钩子
@asynccontextmanager
async def lifespan(_app: FastAPI):
    postgre.init_db()
    await redis.init_db()
    FM.start_scheduler()
    yield
    await redis.close_db()


app = FastAPI(
    title='Ping Card Backend',
    version='1.0.0',
    contact={
        'name': 'Gu Pingan',
        'url': 'https://github.com/gupingan',
        'email': 'g332920287@foxmail.com'
    },
    license_info={
        'name': 'Apache 2.0',
        'url': 'https://www.apache.org/licenses/LICENSE-2.0.html'
    },
    lifespan=lifespan
)
backend_app = FastAPI()
develop_app = FastAPI()

# 挂载子应用
app.mount('/backend', backend_app)
app.mount('/develop', develop_app)
app.mount('/images', StaticFiles(directory=STATIC_IMG_FOLDER), name='static')
# 挂载设置
mount_settings_to_app(backend_app)
mount_settings_to_app(develop_app)
# 注册中间件
backend_middlewares.register_exc_handler(backend_app)
backend_middlewares.register_middlewares(backend_app)
develop_middlewares.register_exc_handler(develop_app)
develop_middlewares.register_middlewares(develop_app)
# 注册路由
backend_router.register_routers(backend_app)
develop_router.register_routers(develop_app)

if get_settings().ENABLE_FAKER_API:
    faker_app = FastAPI()
    app.mount('/faker', faker_app)
    backend_middlewares.register_middlewares(faker_app)
    faker_router.register_routers(faker_app)
    mount_settings_to_app(faker_app)
